import { join, extname } from "path";
import { existsSync, mkdirSync } from "fs";
import { move } from "fs-extra";
import { getUuidString } from "./uuid";

export const existsAndMkdir = (targetDir) => {
  if (!existsSync(targetDir)) {
    mkdirSync(targetDir, { recursive: true });
  }
};

export const saveFiles = async (files: any[], DirName?: string) => {
  const defaultDirUrl = DirName
    ? `/oss/platform/${DirName}/template`
    : `/oss/platform/t1/u1`;
  const defaultDir = join(process.cwd(), `src/static${defaultDirUrl}`);

  existsAndMkdir(defaultDirUrl);

  const res = await Promise.all(
    files.map((file) => {
      const extension = extname(file.originalFilename);
      const newFilename = `${file.newFilename}${extension}`;
      const newPath = join(defaultDir, newFilename);
      return move(file.filepath, newPath).then(() => ({
        fileName: newFilename,
        url: `${defaultDirUrl}/${newFilename}`,
        bucketName: "platform",
        preUrl: `${defaultDirUrl}/${newFilename}`,
        id: getUuidString(),
      }));
    })
  );
  return res;
};
